﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using System.Xml.Linq;
//
using CookComputing.XmlRpc;
//
namespace PerceptiveMCAPI.Types
{
   public class campaignEmailStatsAIMAllOutput : Api_BaseOutput
   {
      public List<campaignEmailStatsAIMAllResults> result { get; set; }
      public campaignEmailStatsAIMAllParms inputParms { get; private set; }
      // --------------------------------------------------------
      public campaignEmailStatsAIMAllOutput( campaignEmailStatsAIMAllInput input )
         : base( input )
      {
         inputParms = input.parms;
         result = new List<campaignEmailStatsAIMAllResults>();
      }
      // --------------------------------------------------- tostring
      public override string ToString()
      {
         return string.Format( "AIM Statis: {0}", this.result.Count );
      }

      #region ================================================================== format setup

      // ---- serial
      internal void Format( string api_Request, string api_Response )
      {
         this.api_Request = api_Request;
         this.api_Response = api_Response;
         // ----------------------------------
         if ( this.api_OutputType == EnumValues.OutputType.JSON )
            outputJSON();
         else if ( this.api_OutputType == EnumValues.OutputType.XML )
            outputXML();
      }

      // ---- xmlrpc
      internal void Format( XmlRpcStruct rpcResult )
      {
         this.api_Request = EnumValues.NotSupplied;
         this.api_Response = EnumValues.NotSupplied;
         // ------------------------
         this.result = FormatStats( rpcResult );
      }

      #endregion

      #region ================================================================= Output

      // ---------------------------------------------------------- outputXML
      private void outputXML()
      {
         XElement xml = XElement.Parse( this.api_Response );
         // error check
         Api_Error error = apiSerial.GetXmlOutputError( xml );
         if ( error != null )
         {
            this.api_ErrorMessages.Add( error );
            return;
         }
         // -------------------------------------------- get values
         DateTime dt;
         try
         {
            IEnumerable<XElement> all = xml.Elements( "struct" );
            foreach ( XElement entry in all )
            {
               campaignEmailStatsAIMAllResults AllResults = new campaignEmailStatsAIMAllResults();
               AllResults.email = entry.Attribute( "key" ).Value;
               if ( entry.HasElements )
               {
                  IEnumerable<XElement> emailResults = entry.Elements( "struct" );
                  foreach ( XElement result in emailResults )
                  {
                     campaignEmailStatsAIMResults results = new campaignEmailStatsAIMResults();
                     results.action = result.Element( "action" ).Value;
                     DateTime.TryParse( result.Element( "timestamp" ).Value, out dt );
                     results.timestamp = dt;
                     results.url = result.Element( "url" ).Value;
                     results.ip = result.Element( "ip" ).Value;
                     AllResults.emailStatsAIM.Add( results );
                  }
               }
               this.result.Add( AllResults );
            }
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ---------------------------------------------------------- outputJSON
      private void outputJSON()
      {
         JavaScriptSerializer jss = new JavaScriptSerializer();

         try
         {
            if ( this.api_Response.Contains( EnumValues.JSONErrorString ) )
            {
               Api_Error err = jss.Deserialize<Api_Error>( this.api_Response );
               this.api_ErrorMessages.Add( err );
            }
            else
            {
               if ( this.api_Response.GetType().IsArray ) return;

               XmlRpcStruct jsonResult = jss.Deserialize<XmlRpcStruct>( this.api_Response );
               this.result = FormatStats( jsonResult );
            }
         }
         catch ( Exception ex )
         {
            this.api_ErrorMessages.Add( apiException.FormatError( ex ) );
         }
      }

      // ---------------------------------------------------------- Formatting
      private List<campaignEmailStatsAIMAllResults> FormatStats( XmlRpcStruct resultsStruct )
      {
         DateTime dt;
         List<campaignEmailStatsAIMAllResults> results = new List<campaignEmailStatsAIMAllResults>();

         foreach ( DictionaryEntry result in resultsStruct )
         {
            campaignEmailStatsAIMAllResults stats = new campaignEmailStatsAIMAllResults();
            stats.email = result.Key.ToString();
            object[] actions = result.Value as object[];
            //
            foreach ( object action_obj in actions )
            {
               campaignEmailStatsAIMResults statAction = new campaignEmailStatsAIMResults();
               IDictionary action = action_obj as IDictionary;

               statAction.action = action["action"].ToString();
               if ( action["url"] != null )
                  statAction.url = action["url"].ToString();
               DateTime.TryParse( action["timestamp"].ToString(), out dt );
               statAction.timestamp = dt;
               statAction.ip = action["ip"].ToString();

               stats.emailStatsAIM.Add( statAction );
            }
            results.Add( stats );
         }
         return results;
      }

      #endregion
   }
}
